package com.wsoft.bpm.component;

import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 倒计时绑定器
 *
 * @Author zhonglj
 * @Date 2025/2/19 17:43
 */
@Component
public class CountDownLatchMatcher {
    private final ConcurrentHashMap<String, CountDownLatch> matcherMap = new ConcurrentHashMap<>();

    // 带防御性检查的通知
    public void notify(String taskId) {
        CountDownLatch latch = matcherMap.remove(taskId);
        if (latch != null && latch.getCount() > 0) {
            latch.countDown();
        }
    }

    public boolean keepGoing(String taskId) {
        return !matcherMap.containsKey(taskId);
    }

    // 带超时的等待（防死锁）
    public boolean waitWithTimeout(String taskId, long timeoutMs) throws InterruptedException {
        CountDownLatch latch = matcherMap.computeIfAbsent(taskId, k -> new CountDownLatch(1));
        return latch.await(timeoutMs, TimeUnit.MILLISECONDS);
    }
}
